package com.arvato.common.listen;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
/**
 * 
 * @author: smallking
 * 
 * @Descibe:重写spring文件上传解析器 实现文件上传进度条功能(这个类是我之前一个spring项目使用的，不知道在这儿还能用吧)
 * 具体思路就是 重写spring文件上传解析器，将文件上传进度存储在session里面。前台轮询获取上传进度
 * 
 * @Date: 2018年6月5日  下午12:07:07
 */
public class CustomMultipartResolver extends CommonsMultipartResolver{

		@Autowired  
	    private FileUploadProgressListener progressListener;  
	  
	    public void setFileUploadProgressListener(  
	            FileUploadProgressListener progressListener) {  
	        this.progressListener = progressListener;  
	    }  
	    
	    @Override  
	    public MultipartParsingResult parseRequest(HttpServletRequest request)  
	            throws MultipartException {  
	        String encoding = determineEncoding(request);
	        FileUpload fileUpload = prepareFileUpload(encoding);  
	        progressListener.setSession(request.getSession());  
	        fileUpload.setProgressListener(progressListener);  
	        try {  
	            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);  
	            return parseFileItems(fileItems, encoding);  
	        }  
	        catch (FileUploadBase.SizeLimitExceededException ex) {  
	            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);  
	        }  
	        catch (FileUploadException ex) {  
	            throw new MultipartException("Could not parse multipart servlet request", ex);  
	        }  
	    }  
}
